/**
 * Project: dbcompare
 * 
 * File Created at 2010-5-27
 * $Id$
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.alibaba.incubator.loadtestermini.util.distribution;

/**
 * (created at 2010-5-27)
 * 
 * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
 */
public class IntervalItem<T> implements Comparable<IntervalItem<T>> {

    private double from;
    private double to;
    private T value;

    public T getValue() {
        return value;
    }

    public double getFrom() {
        return from;
    }

    public double getTo() {
        return to;
    }

    public double getRange() {
        return to - from;
    }

    /**
     * @param from include
     * @param to exclude
     * @param nodeExecutor must not be null
     */
    public IntervalItem(double from, double to, T value) {
        if (from > to)
            throw new IllegalArgumentException("'from' must <= 'to'! But " + from + ">" + to);
        if (value == null)
            throw new IllegalArgumentException("'value' is required!");
        this.from = from;
        this.to = to;
        this.value = value;
    }

    public boolean contains(double num) {
        return (num >= from) && (num < to);
    }

    private static final int THIS_IS_GREATER = -1;

    /**
     * compare range only
     */
    public int compareTo(IntervalItem<T> that) {
        if (that == this)
            return 0;
        if (that == null)
            return THIS_IS_GREATER;
        final double thisRange = this.to - this.from;
        final double thatRange = that.to - that.from;
        if (thisRange > thatRange)
            return THIS_IS_GREATER;
        else if (thisRange < thatRange)
            return -THIS_IS_GREATER;
        return 0;
    }

    public String toString() {
        return new StringBuilder().append(getClass().getSimpleName())
                                  .append("@")
                                  .append(hashCode())
                                  .append("{")
                                  .append("from=")
                                  .append(from)
                                  .append(", to=")
                                  .append(to)
                                  .append(", value=")
                                  .append(value)
                                  .append("}")
                                  .toString();
    }
}
